#include "GUIEvent.h"
#include "motor.h"

int isGoodClickReady = 0;

int countTime = 30;

int timer_id = 0;

int timer_motor_id = 0;

pthread_t finger_thread_id = 0;

// 点击处理事件
void click_event(int x, int y, ClickType clicktype)
{
    if (currentPage == MAIN_PAGE)
    {
        main_page_click_event(x, y, clicktype);
    }
    else if (currentPage == PAY_PAGE)
    {
        switch (currentPayType)
        {
        case WECHAT_PAY:
            wechat_pay_click_event(x, y, clicktype);
            break;
        case FINGER_PAY:
            finger_pay_click_event(x, y, clicktype);
            break;
        default:
            break;
        }
    }
    else if (currentPage == MAIN_SUCCESS_PAGE)
    {
        pay_success_click_event(x, y, clicktype);
    }
    else
    {
        printf("click_event: unknown page\n");
    }
}

// 主界面点击处理函数
void main_page_click_event(int x, int y, ClickType clicktype)
{
    printf("main_page_click_event: (%d, %d)\n", x, y);
    for (int i = 0; i < GOOD_NUM; i++)
    {
        if (is_in_area(x, y, goodArea[i].x, goodArea[i].y, goodArea[i].width, goodArea[i].height))
        {
            // 如果当前点击的商品为当前选中商品
            if (cursorGoodIndex == i)
            {

                // 只有点击抬起才会响应
                if (clicktype == CLICK_UP)
                {
                    // 计算计时器的时间是否超过20ms，如果超过则执行打印
                    printf("main_page_click_event: enter pay page\n");
                    currentPage = PAY_PAGE;

                    // 进入支付界面
                    enter_pay_page_event(cursorGoodIndex);
                }
            }
            else
            {
                // 重绘前面的商品
                draw_bitmap(goodsInfo[cursorGoodIndex].picturePath, goodArea[cursorGoodIndex].x, goodArea[cursorGoodIndex].y, goodArea[cursorGoodIndex].width, goodArea[i].height);

                // 重绘前面的虚线为白色
                draw_dashed_border(goodArea[cursorGoodIndex].x - DASH_MARGIN, goodArea[cursorGoodIndex].y - DASH_MARGIN, GOOD_WIDTH + 2 * DASH_MARGIN, GOOD_HEIGHT + 2 * DASH_MARGIN, BG_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);

                // 在当前商品添加虚线
                draw_dashed_border(goodArea[i].x - DASH_MARGIN, goodArea[i].y - DASH_MARGIN, GOOD_WIDTH + 2 * DASH_MARGIN, GOOD_HEIGHT + 2 * DASH_MARGIN, DASH_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);

                cursorGoodIndex = i;
            }
            break;
        }
    }
}

// 微信支付页点击处理函数
void wechat_pay_click_event(int x, int y, ClickType clicktype)
{
    printf("wechat_pay_click_event: (%d, %d)\n", x, y);
    // draw_dashed_border(426 - DASH_MARGIN, 133 - DASH_MARGIN, 157 + 2 * DASH_MARGIN, 35 + 2 * DASH_MARGIN, DASH_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);
    // 判断点击“返回”文字区域（根据你绘制的位置）
    if (is_in_area(x, y, 402, 401, 70, 35)) // 假设“返回”文字宽高为 80x40
    {
        pay_back_click_event(); // 调用返回事件
    }
    else if (is_in_area(x, y, 601, 136, 120, 35))
    { // 点击指纹支付文本
        // 清空微信支付码
        fill_color(BG_COLOR, weChatPayImgArea.x, weChatPayImgArea.y, weChatPayImgArea.width, weChatPayImgArea.height);

        // 清空微信支付边框
        draw_dashed_border(426 - DASH_MARGIN, 133 - DASH_MARGIN, 157 + 2 * DASH_MARGIN, 35 + 2 * DASH_MARGIN, BG_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);

        // 绘制指纹支付提示文字
        font_display_text(439, 255, "请在指纹检测处支付", 35, BUTTON_TEXT_COLOR);

        // 画指纹支付文本边框
        draw_dashed_border(600 - DASH_MARGIN, 133 - DASH_MARGIN, 130 + 2 * DASH_MARGIN, 35 + 2 * DASH_MARGIN, DASH_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);

        // 修改当前支付方式
        currentPayType = FINGER_PAY;

        start_golden_finger_thread();
    }
    else if (is_in_area(x, y, 581, 401, 180, 35))
    {
        enter_pay_success_page_event();
    }
}

// 进入支付成功界面
void enter_pay_success_page_event()
{
    motor_control(1);

    timer_motor_id = start_timer(2, close_motor_event);

    // 清空支付界面全部内容
    fill_color(BG_COLOR, 330, 0, SCREEN_WIDTH - 330, SCREEN_HEIGHT);

    // 绘制支付成功文本
    font_display_text(495, 100, "支付成功", 40, BUTTON_TEXT_COLOR);

    // 绘制取出货物文本
    font_display_text(400, 170, "请在下方取出您的货物", 40, BUTTON_TEXT_COLOR);

    // 绘制返回初始界面按钮
    font_display_text(440, 350, "返回初始界面", 35, BUTTON_TEXT_COLOR);

    // 返回倒计时
    font_display_text(650, 350, "30秒", 35, BUTTON_TEXT_COLOR);

    currentPage = MAIN_SUCCESS_PAGE;

    countTime = 30;

    // 开启一个计时器
    timer_id = start_timer(1, swapCountTime);
}

// 关闭电机事件
void close_motor_event()
{
    motor_control(0);
}

// 改变倒计时显示
void swapCountTime()
{
    stop_timer(timer_id);
    if (currentPage != MAIN_SUCCESS_PAGE)
    {
        return;
    }

    countTime--;
    fill_color(BG_COLOR, 650, 350, SCREEN_WIDTH - 440, SCREEN_HEIGHT - 350);

    char str[128];
    sprintf(str, "%d秒", countTime);

    font_display_text(650, 350, str, 35, BUTTON_TEXT_COLOR);

    if (countTime == 0)
    {
        pay_success_back_click_event();
    }
    else
    {
        timer_id = start_timer(1, swapCountTime);
    }
}

// 指纹支付页点击处理函数
void finger_pay_click_event(int x, int y, ClickType clicktype)
{
    printf("finger_pay_click_event: (%d, %d)\n", x, y);
    // currentPayType == FINGER_PAY;

    // 判断点击“返回”文字区域（根据你绘制的位置）
    if (is_in_area(x, y, 402, 401, 70, 35)) // 假设“返回”文字宽高为 80x40
    {
        pay_back_click_event();
        join_golden_finger_thread();
    }
    else if (is_in_area(x, y, 426, 133, 157, 35))
    {
        // 清空指纹支付文字
        fill_color(BG_COLOR, 439, 255, SCREEN_WIDTH - 439, 35);

        // 清空指纹支付边框
        draw_dashed_border(600 - DASH_MARGIN, 133 - DASH_MARGIN, 130 + 2 * DASH_MARGIN, 35 + 2 * DASH_MARGIN, BG_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);

        // 绘制微信支付边框
        draw_dashed_border(426 - DASH_MARGIN, 133 - DASH_MARGIN, 157 + 2 * DASH_MARGIN, 35 + 2 * DASH_MARGIN, DASH_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);

        // 绘制微信支付码
        draw_bitmap(WeChatPayImgPath, weChatPayImgArea.x, weChatPayImgArea.y, weChatPayImgArea.width, weChatPayImgArea.height);

        currentPayType = WECHAT_PAY;
        join_golden_finger_thread();
    }
}

// 支付成功页点击处理函数
void pay_success_click_event(int x, int y, ClickType clicktype)
{
    printf("pay_success_click_event: (%d, %d)\n", x, y);

    if (is_in_area(x, y, 440, 350, 250, 35))
    {
        pay_success_back_click_event();
        stop_timer(timer_id);
    }
}

// 支付成功并返回初始界面
void pay_success_back_click_event()
{
    pay_back_click_event();
}

// 判断点击区域是否在指定区域内
int is_in_area(int x, int y, int x1, int y1, int width, int height)
{
    return x >= x1 && x <= x1 + width && y >= y1 && y <= y1 + height;
}

// 进入支付界面
void enter_pay_page_event(int current_good_index)
{

    // 清空商品列表内容
    fill_color(BG_COLOR, goodGroupArea.x - DASH_WIDTH, goodGroupArea.y - DASH_WIDTH, goodGroupArea.width + 5 * DASH_WIDTH, goodGroupArea.height + 5 * DASH_WIDTH);
    // motor_control(1);
    // usleep(1000*1000);
    // motor_control(0);

    // 绘制商品图片
    draw_bitmap(goodsInfo[cursorGoodIndex].picturePath, 373, 17, GOOD_WIDTH, GOOD_HEIGHT);

    // 获取商品信息
    const char *name = goodsInfo[cursorGoodIndex].name;
    double price = goodsInfo[cursorGoodIndex].price;

    // 构造显示文本
    char infoLine1[128];
    char infoLine2[128];

    snprintf(infoLine1, sizeof(infoLine1), "%s * 1", name);
    snprintf(infoLine2, sizeof(infoLine2), "价格：%g 元", price);

    // 写商品信息
    font_display_text(470, 47, infoLine1, 35, BUTTON_TEXT_COLOR);
    font_display_text(615, 47, infoLine2, 35, BUTTON_TEXT_COLOR);

    // 绘制按钮
    font_display_text(402, 401, "返回", 35, BUTTON_TEXT_COLOR);
    font_display_text(581, 401, "我已成功支付", 35, BUTTON_TEXT_COLOR);
    font_display_text(426, 136, "二维码支付", 35, BUTTON_TEXT_COLOR);
    font_display_text(601, 136, "指纹支付", 35, BUTTON_TEXT_COLOR);

    currentPage = PAY_PAGE;
    currentPayType = WECHAT_PAY;

    draw_dashed_border(426 - DASH_MARGIN, 133 - DASH_MARGIN, 157 + 2 * DASH_MARGIN, 35 + 2 * DASH_MARGIN, DASH_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);

    draw_bitmap(WeChatPayImgPath, weChatPayImgArea.x, weChatPayImgArea.y, weChatPayImgArea.width, weChatPayImgArea.height);
}

// 返回按钮点击事件处理函数
void pay_back_click_event()
{

    printf("pay_back_click_event: returning to main page\n");
    currentPage = MAIN_PAGE;

    // 清屏并重新绘制主页面
    fill_color(BG_COLOR, goodGroupArea.x, goodGroupArea.y - 10, SCREEN_WIDTH - goodGroupArea.x, 10 + SCREEN_HEIGHT - goodGroupArea.y);

    for (int i = 0; i < GOOD_NUM; i++)
    {
        draw_bitmap(goodsInfo[i].picturePath, goodArea[i].x, goodArea[i].y, goodArea[i].width, goodArea[i].height);
        char text[264];
        sprintf(text, "%s %.1f", goodsInfo[i].name, goodsInfo[i].price);
        if (i == 6)
        {
            font_display_text(goodArea[i].x - 15, goodArea[i].y + GOOD_HEIGHT + 5, text, 30, BUTTON_TEXT_COLOR);
        }
        else if (i == 3)
        {
            font_display_text(goodArea[i].x - 3, goodArea[i].y + GOOD_HEIGHT + 5, text, 30, BUTTON_TEXT_COLOR);
        }
        else if (i == 8)
        {
            font_display_text(goodArea[i].x - 3, goodArea[i].y + GOOD_HEIGHT + 5, text, 30, BUTTON_TEXT_COLOR);
        }
        else
        {
            font_display_text(goodArea[i].x, goodArea[i].y + GOOD_HEIGHT + 5, text, 30, BUTTON_TEXT_COLOR);
        }
    }

    // 恢复虚线边框
    draw_dashed_border(goodArea[cursorGoodIndex].x - DASH_MARGIN, goodArea[cursorGoodIndex].y - DASH_MARGIN,
                       GOOD_WIDTH + 2 * DASH_MARGIN, GOOD_HEIGHT + 2 * DASH_MARGIN,
                       DASH_COLOR, DASH_WIDTH, DASH_LEN, GAP_LEN);

    currentPage = MAIN_PAGE;
}

// 线程函数，用来执行 golden_finger
void *golden_finger_thread(void *arg)
{
    // 在新的线程中调用 golden_finger
    golden_finger();
    return NULL;
}

// 创建并启动一个新的线程，执行 golden_finger
int start_golden_finger_thread(void)
{
    int result = pthread_create(&finger_thread_id, NULL, golden_finger_thread, NULL);

    if (result != 0)
    {
        printf("Error creating thread: %d\n", result);
        return -1; // 线程创建失败
    }

    pthread_detach(finger_thread_id); // 使线程自动清理资源
    return 0;                         // 线程创建成功
}

// 回收线程资源
int join_golden_finger_thread(void)
{
    int result = pthread_join(finger_thread_id, NULL);

    if (result != 0)
    {
        printf("Error joining thread: %d\n", result);
        return -1; // 线程回收失败
    }

    close_finger_device();

    printf("Thread joined successfully.\n");
    return 0; // 线程回收成功
}
